package com.black.app.service.impl.my;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.black.app.domain.my.AppMyHeatDetail;
import com.black.app.domain.req.my.mydata.AppMyHeatDetailAddReq;
import com.black.app.service.my.AppMyHeatDetailService;
import com.black.app.mapper.my.AppMyHeatDetailMapper;
import com.black.common.exception.ServiceException;
import com.black.common.utils.MessageUtils;
import com.black.common.utils.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
* @author 18494
* @description 针对表【app_my_heat_detail(热量记录表)】的数据库操作Service实现
* @createDate 2024-10-23 20:49:29
*/
@Service
public class AppMyHeatDetailServiceImpl extends ServiceImpl<AppMyHeatDetailMapper, AppMyHeatDetail>
    implements AppMyHeatDetailService{

    @Override
    public boolean addCalorie(AppMyHeatDetailAddReq req) {
        req.setUserId(SecurityUtils.getAppLoginUser().getUserId());

        // 判断日期是否存在
        if (this.baseMapper.exists(new LambdaQueryWrapper<AppMyHeatDetail>().eq(AppMyHeatDetail::getDate, req.getDate()))) {
            throw new ServiceException(MessageUtils.message("app.my.detail.date.exists"));
        }
        AppMyHeatDetail newEntity = new AppMyHeatDetail();
        BeanUtils.copyProperties(req, newEntity);
        boolean save = this.save(newEntity);

        return save;
    }

    @Override
    public PageInfo<AppMyHeatDetail> getCalorie(AppMyHeatDetailAddReq req) {
        req.setUserId(SecurityUtils.getAppLoginUser().getUserId());

        return PageHelper.startPage(req.getPageNum(), req.getPageSize()).doSelectPageInfo(() -> {
            this.baseMapper.getCalorie(req);
        });
    }

    @Override
    public boolean deleteById() {
        // 获取当前登录用户的id
        Long userId = SecurityUtils.getAppLoginUser().getUserId();
        // 删除AppMyHeatDetail表中的id最大的数据
        int id = this.baseMapper.selectOne(new LambdaQueryWrapper<AppMyHeatDetail>()
                    .eq(AppMyHeatDetail::getUserId, userId)
                    .orderByDesc(AppMyHeatDetail::getId).last("limit 1")).getId();
        // 删除
        boolean result = this.removeById(id);
        return result;
    }
}




